<template>
  <div class="add-invoice">
    <a-page-header title="添加发票" @back="router.back()">
      <template #subtitle>
        <a-tag :color="sellerName === '顺丰' ? 'blue' : 'green'">{{ sellerName }}</a-tag>
      </template>
    </a-page-header>
    <div class="main">
      <a-form
        ref="addFormRef"
        :model="invoiceInfo"
        auto-label-width
        :rules="addRules"
        :layout="isPhone ? 'vertical' : 'horizontal'"
      >
        <a-form-item label="开票名称" field="buyer">
          <a-auto-complete
            v-model="invoiceInfo.buyer"
            :data="data.templateList.map(v => v.buyer) as string[]"
            @select="select"
          ></a-auto-complete>
        </a-form-item>
        <a-form-item label="税号" field="taxNumber">
          <a-input v-model="invoiceInfo.taxNumber"></a-input>
        </a-form-item>
        <a-form-item label="地址" field="address">
          <a-input v-model="invoiceInfo.address"></a-input>
        </a-form-item>
        <a-form-item label="开户银行" field="bank">
          <a-input v-model="invoiceInfo.bank"></a-input>
        </a-form-item>
        <a-form-item label="银行账号" field="bankAccount">
          <a-input v-model="invoiceInfo.bankAccount"></a-input>
        </a-form-item>
        <a-form-item label="联系电话" field="phone">
          <a-input v-model="invoiceInfo.phone"></a-input>
        </a-form-item>
        <a-form-item label="开票金额" field="invoiceCount">
          <a-input v-model="invoiceInfo.invoiceCount as string"></a-input>
        </a-form-item>
        <a-form-item label="发票类型" field="invoiceType">
          <a-select
            v-model="invoiceInfo.invoiceType"
            :options="invoiceTypes"
          ></a-select>
        </a-form-item>
        <a-form-item label="月份" field="month">
<!--          <a-input v-model="invoiceInfo.month"></a-input>-->
          <a-month-picker v-model="invoiceInfo.month" format="YYYY年MM月" style="width: 100%;"></a-month-picker>
        </a-form-item>
        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="invoiceInfo.remark"
            :auto-size="{ minRows: 3 }"
            :max-length="500"
            show-word-limit
          ></a-textarea>
        </a-form-item>
      </a-form>
      <div class="handle-button">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="submit">确定</a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { invoiceTypes } from "@/views/invoice/enums";
import {
  addCommonTemplate,
  addInvoice,
  checkHasTemplate,
  CommonTemplate,
  Invoice,
  listAllTemplate,
} from "@/api/invoiceController";
import { onMounted, reactive, ref } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import router from "@/router";
import { useWindowSize } from "@vueuse/core";
import { computed } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const sellerName = computed(() => {
  if (route.name === "添加发票(顺丰)") {
    return "顺丰";
  }
  if (route.name === "添加发票(合丰)") {
    return "合丰";
  }
});

const { width } = useWindowSize();
const isPhone = computed(() => {
  return width.value < 768;
});
let invoiceInfo = reactive<Invoice>({});
const data = ref({
  templateList: [] as CommonTemplate[],
});
const addFormRef = ref();
const addRules = ref({
  buyer: [{ required: true, message: "请输入开票名称", trigger: "blur" }],
  taxNumber: [{ required: true, message: "请输入税号", trigger: "blur" }],
  invoiceCount: [
    { required: true, message: "请输入开票金额", trigger: "blur" },
  ],
  invoiceType: [{ required: true, message: "请选择发票类型", trigger: "blur" }],
});

const submit = () => {
  addFormRef.value.validate((error: boolean) => {
    if (!error) {
      console.log(invoiceInfo);
      addInvoice(invoiceInfo, sellerName.value).then((res) => {
        Message.success("添加成功");
        if (res.buyer) {
          checkHasTemplate(res.buyer, sellerName.value).then((res1) => {
            if (!res1) {
              Modal.warning({
                title: "提示",
                content: `监测到你没有将「${res.buyer}」添加到常用开票模版中，是否添加。添加后可到模版中心维护。`,
                hideCancel: false,
                onOk: () => {
                  addCommonTemplate(res as CommonTemplate).then(() => {
                    Message.success("添加模版成功");
                    if (sellerName.value === "顺丰") {
                      router.push("/invoice_sf");
                    }
                    if (sellerName.value === "合丰") {
                      router.push("/invoice_hf");
                    }
                  });
                },
                onBeforeCancel: () => {
                  if (sellerName.value === "顺丰") {
                    router.push("/invoice_sf");
                  }
                  if (sellerName.value === "合丰") {
                    router.push("/invoice_hf");
                  }
                  return true;
                },
              });
            } else {
              if (sellerName.value === "顺丰") {
                router.push("/invoice_sf");
              }
              if (sellerName.value === "合丰") {
                router.push("/invoice_hf");
              }
            }
          });
        }
      });
    }
  });
};

const getTemplateList = () => {
  listAllTemplate(sellerName.value).then((res) => {
    data.value.templateList = (res as CommonTemplate[]) || [];
  });
};

const select = (value: string) => {
  const template = data.value.templateList.find((v) => v.buyer === value);
  if (template) {
    Object.assign(invoiceInfo, template);

    delete invoiceInfo.createTime
    delete invoiceInfo.updateTime

    if(template?.defaultInvoiceType) {
      invoiceInfo.invoiceType = template.defaultInvoiceType
    }
  }
};

onMounted(() => {
  getTemplateList();
});
</script>

<style lang="scss" scoped>
@media (max-width: 768px) {
  .main {
    padding: 0 20px;
  }
}

.main {
  max-width: 500px;
  margin: auto;
  padding-bottom: 50px;

  .handle-button {
    text-align: center;
  }
}
</style>
